package com.app.core.web.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.app.core.common.AppCons;
import com.app.core.session.UserSession;
import com.app.core.web.context.RequestContext;
import com.app.core.web.util.AppContextUtil;
import com.app.core.web.util.CookieUtils;

/**
 * @登录检验过滤器
 */
public class AttachFilter implements Filter {

    private static final Logger log = LoggerFactory.getLogger(AttachFilter.class);

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = ((HttpServletRequest) servletRequest).getSession();

        if (request.getRequestURL().toString().startsWith(AppCons.FILEUPLOAD_AUTH_PATH)) {

            UserSession userSession = null;/* 获取用户cookie中存储的session id */
            Cookie userCookie = CookieUtils.getCookie(request, AppCons.LOGIN_USER_SESSION_ID_ADMIN);
            if (userCookie == null) {
                noAuth(response);
                return;
            }
            String clientSessionId = userCookie.getValue();
            if (AppCons.RUN_MODE_ALONE) {
                userSession = (UserSession) session.getAttribute(AppCons.LOGIN_USER_SESSION_ADMIN);
            } else {
                /* 查询中心缓存 */
                userSession = AppContextUtil.getRedisCache().get(clientSessionId);
            }

            if (userSession == null) {
                noAuth(response);
                return;
            }
        }

        chain.doFilter(servletRequest, servletResponse);
    }

    private void noAuth(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-type", "application/json;charset=UTF-8");
        response.sendError(401, "未授权");
        PrintWriter out = response.getWriter();
        out.print("未授权");
        out.flush();
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
}
